/*
1.接收客户端 request，并将 request 中带的 header 写入 response header
2.读取当前系统的环境变量中的 VERSION 配置，并写入 response header
3.Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出
4.当访问 localhost/healthz 时，应返回200
*/

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/pprof"
	"os"

	_ "net/http/pprof"
)

func main() {

	mux := http.NewServeMux()
	mux.HandleFunc("/", rootHandler)
	mux.HandleFunc("/healthz", healthz)			//3，4

	err := http.ListenAndServe(":80", mux)
	if err != nil {
		log.Fatal(err)
	}

}

func healthz(w http.ResponseWriter, r *http.Request) {
	//3,4
	w.WriteHeader(http.StatusOK)
	_, _ = io.WriteString(w, "200:ok")
	log.Println("/healthz Client ip and port is " + r.RemoteAddr + " Status Code is " + http.StatusText(200))
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("entering root handler")

	ver := os.Getenv("VERSION")
	//系统变量中没有版本信息
	if ver == "" {
		ver = "0.0.0"
	}

	user := r.URL.Query().Get("user")
	if user != "" {
		io.WriteString(w, fmt.Sprintf("hello [%s]\n", user))
	} else {
		io.WriteString(w, "hello [stranger]\n")
	}
	io.WriteString(w, "===================Details of the http request header:============\n")
	
	//1
	for k, v := range r.Header {
		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
	}
	//2
	io.WriteString(w, fmt.Sprintf("VERSION:%s\n", ver))
}
